package com.sdhs.paas.flux.app;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.sdhs.paas.flux.model.User;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
public class HelloController {
	private static final int DELAY_PER_ITEM_MS = 100;
    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("Welcome to reactive world ~");
    }
    
    @GetMapping("/client")
    public void webClientTest1() throws InterruptedException {
        WebClient webClient = WebClient.create("http://localhost:8087");   // 1
        Mono<User> resp = webClient
                .get().uri("/user/username") // 2
                .retrieve() // 3
                .bodyToMono(User.class);  // 4
        resp.subscribe(System.out::println);    // 5
        TimeUnit.SECONDS.sleep(1);  // 6
    }
    
    @GetMapping("/fluxclient")
    public void webClientTest2() throws InterruptedException {
        WebClient webClient = WebClient.builder().baseUrl("http://localhost:8087").build(); // 1
        webClient
                .get().uri("/user")
                .accept(MediaType.APPLICATION_STREAM_JSON) // 2
                .exchange() // 3
                .flatMapMany(response -> response.bodyToFlux(User.class))   // 4
                .doOnNext(System.out::println)  // 5
//                .delayElements(Duration.ofMillis(DELAY_PER_ITEM_MS));
                .blockLast();   // 6
    }
    
    @GetMapping("/fluxIndex")
    public Flux<User> fluxIndex() throws InterruptedException {
        WebClient webClient = WebClient.builder().baseUrl("http://localhost:8087").build(); // 1
        Flux<User> fluxUser=webClient
                .get().uri("/flux/index")
                .accept(MediaType.APPLICATION_STREAM_JSON) // 2
                .exchange() // 3
                .flatMapMany(response -> response.bodyToFlux(User.class));   // 4
        return fluxUser;
    }
    
 
}
